package com.appprogram.baseapppackage.widget;

import android.graphics.Bitmap;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;

import com.just.agentweb.WebViewClient;

import java.io.ByteArrayInputStream;

import static com.appprogram.baseapppackage.widget.LoadRule.loadRule;


/**
 * Created by Android Studio .
 * Project：SixPulsesPackage com.sixpulsespackage.union
 * Date：2019/5/23 8:58
 * Introduce：SixPulsesPackage
 */
public class MyWebViewClient extends WebViewClient {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        view.getSettings().setBlockNetworkImage(false);
        super.onPageFinished(view, url);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        String url = request.getUrl().toString();
        return loadRule(view, url);
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        //此处 屏蔽广告
        if (isAdDomain(request.getUrl().toString())) {
            return createEmptyResource();
        }
        return super.shouldInterceptRequest(view, request);
    }

    private WebResourceResponse createEmptyResource() {
        byte[] aByte = new byte[]{};
        return new WebResourceResponse("text/plain", "utf-8", new ByteArrayInputStream(aByte));
    }

    private boolean isAdDomain(String url) {
        //不是本站域名 一律屏蔽
        return (!url.startsWith("https://m.sgzww.com/"));
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return loadRule(view, url);
    }

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
        view.stopLoading();
        view.loadUrl("about:blank");
        view.loadUrl("file:///android_asset/error.html");
    }
}
